package week_five;

public class MinimumDaysToMakeMBouquets_1482 {
    public int minDays(int[] bloomDay, int m, int k) {
        int l = 1, r = (int) 1e9 + 1;
        while (l < r) {
            int mid = (l + r) / 2;
            if (isValidDay(bloomDay, m, k, mid)) r = mid;
            else l = mid + 1;
        }
        if (l == 1e9 + 1) return -1;
        return l;
    }

    private boolean isValidDay(int[] bloomDay, int m, int k, int T) {
        int consecutive = 0;//连续的花朵
        int bouquet = 0;//花束数量
        for (int i = 0; i < bloomDay.length && bouquet < m; i++) {
            if (bloomDay[i] <= T) {
                consecutive++;
                if (consecutive == k) {
                    bouquet++;
                    consecutive = 0;
                }
            } else {
                consecutive = 0;
            }
        }
        return bouquet >= m;
    }
}
